Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:

s: "barfoothefoobarman"

words: ["foo", "bar"]

You should return the indices: [0,9]. (order does not matter).

Solution:

  1. public class Solution {
  2. public List<Integer> findSubstring(String s, String[] words) {
  3. List<Integer> res = new ArrayList<Integer>();
  4. int m = words.length;
  5. int n = words[0].length();
  6. int len = m * n;
  7. // build the hash map
  8. Map<String, Integer> map = new HashMap<String, Integer>();
  9. for (int i = 0; i < words.length; i++) {
  10. String word = words[i];
  11. int count = map.containsKey(word) ? map.get(word) + 1 : 1;
  12. map.put(word, count);
  13. }
  14. for (int i = 0; i < s.length() - len + 1; i++) {
  15. Map<String, Integer> temp = new HashMap<String, Integer>(map);
  16. for (int j = i; j < i + len; j += n) {
  17. String str = s.substring(j, j + n);
  18. if (temp.containsKey(str)) {
  19. int count = temp.get(str) - 1;
  20. if (count == 0) {
  21. temp.remove(str);
  22. } else {
  23. temp.put(str, count);
  24. }
  25. } else {
  26. break;
  27. }
  28. }
  29. if (temp.size() == 0) {
  30. res.add(i);
  31. }
  32. }
  33. return res;
  34. }
  35. }